<template>
    <el-form :model="product" ref="productForm" label-width="100px" label-position="top" class="compact-form">
      <el-row :gutter="20">
        <!-- 商品名称 -->
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name" :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
            <el-input v-model="product.name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
        </el-col>
  
        <!-- 商品分类 -->
        <el-col :span="12">
          <el-form-item label="商品分类" prop="categoryId" :rules="[{ required: true, message: '请选择商品分类', trigger: 'change' }]">
            <el-select v-model="product.categoryId" placeholder="请选择分类">
              <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
  
      <!-- 封面上传 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品封面">
            <el-upload action="/file/upload/file" :on-success="handleCoverUploadSuccess" :before-upload="beforeImageUpload" auto-upload class="upload-demo">
              <el-button slot="trigger">封面上传</el-button>
              <template #tip>仅支持jpg/png格式，大小不超过2MB。</template>
            </el-upload>
            <div v-if="product.imgPath">
              <img :src="product.imgPath" alt="封面预览" style="max-width: 100px; margin-top: 10px;" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
  
      <!-- 如果选择分类为表情包 (categoryId == 2)，展示插入表情包功能 -->
      <el-row v-if="product.categoryId === 2" :gutter="20">
        <el-col :span="12">
          <el-form-item label="插入表情包">
            <el-upload action="/file/upload/file" :on-success="handleEmojiUploadSuccess" :before-upload="beforeImageUpload" auto-upload class="upload-demo">
              <el-button slot="trigger">插入表情包</el-button>
              <template #tip>仅支持jpg/png格式，大小不超过2MB。</template>
            </el-upload>
          </el-form-item>
        </el-col>
  
        <!-- 展示插入的表情包列表 -->
        <el-col :span="12">
          <el-form-item label="已插入的表情包">
            <div v-if="emojiList.length > 0">
              <el-image v-for="(emoji, index) in emojiList" :key="index" :src="emoji.emojiUrl" style="max-width: 50px; margin-right: 10px;"></el-image>
            </div>
            <div v-else>
              <span>暂无表情包</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
  
      <el-row :gutter="20">
        <!-- 商品标题 -->
        <el-col :span="12">
          <el-form-item label="商品标题" prop="title" :rules="[{ required: true, message: '请输入商品标题', trigger: 'blur' }]">
            <el-input v-model="product.title" placeholder="请输入商品标题"></el-input>
          </el-form-item>
        </el-col>
  
        <!-- 商品信息 -->
        <el-col :span="12">
          <el-form-item label="商品信息" prop="info" :rules="[{ required: true, message: '请输入商品信息', trigger: 'blur' }]">
            <el-input v-model="product.info" type="textarea" placeholder="请输入商品信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
  
      <el-row :gutter="20">
        <!-- 商品价格和折扣价放在同一行 -->
        <el-col :span="6">
          <el-form-item label="价格" prop="price" :rules="[{ required: true, message: '请输入价格', trigger: 'blur' }]">
            <el-input v-model="product.price" placeholder="请输入价格"></el-input>
          </el-form-item>
        </el-col>
  
        <el-col :span="6">
          <el-form-item label="折扣价" prop="discountPrice">
            <el-input v-model="product.discountPrice" placeholder="请输入折扣价"></el-input>
          </el-form-item>
        </el-col>
  
        <!-- 是否上架 -->
        <el-col :span="6">
          <el-form-item label="是否上架">
            <el-switch v-model="product.onSale"></el-switch>
          </el-form-item>
        </el-col>
  
        <!-- 库存数量 -->
        <el-col :span="6">
          <el-form-item label="库存数量" prop="num" :rules="[{ required: true, message: '请输入库存数量', trigger: 'blur' }]">
            <el-input v-model="product.num" placeholder="请输入库存数量"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
  
      <el-row :gutter="20">
        <!-- 限购数量 -->
        <el-col :span="12">
          <el-form-item label="限购数量" prop="limitNum" :rules="[{ required: true, message: '请输入限购数量', trigger: 'blur' }]">
            <el-input v-model="product.limitNum" placeholder="请输入限购数量"></el-input>
          </el-form-item>
        </el-col>
  
        <!-- 商家信息 -->
        <el-col :span="12">
          <el-form-item label="商家名称" prop="bossName" :rules="[{ required: true, message: '请输入商家名称', trigger: 'blur' }]">
            <el-input v-model="product.bossName" placeholder="请输入商家名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
  
      <!-- 提交和重置按钮 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </template>
  
  <script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import axios from 'axios';
import router from '@/router';
  
  // 商品数据结构
  const product = ref({
    name: '',
    categoryId: null,
    title: '',
    info: '',
    price: '',
    discountPrice: '',
    onSale: false,
    num: 0,
    limitNum: 0,
    bossName: '',
    bossAvatar: '',
    imgPath: '',  // 封面图片URL
    bossId: 1
  });
  
  // 存储表情包列表
  const emojiList = ref<Array<{ emojiUrl: string; categoryId: number; productId: number }>>([]);
  
  // 商品分类，通常从后端获取
  const categories = ref([
    { id: 1, name: '电子产品' },
    { id: 2, name: '表情包' }, 
    { id: 3, name: '食品' },
    { id: 4, name: '小说' }
  ]);
  
  // 上传封面图片成功后的回调
  const handleCoverUploadSuccess = (response: any, file: File) => {
    product.value.imgPath = response.path; // 假设返回的数据中有图片URL
  };
  
  // 上传表情包图片成功后的回调
  const handleEmojiUploadSuccess = (response: any, file: File) => {
    const emoji = {
      emojiUrl: response.path,  // 上传成功后返回的路径
      categoryId: 2,            // 表情包分类固定为 2
      productId: 0              // 提交时更新为真实 productId
    };
    emojiList.value.push(emoji);
  };
  
  // 图片上传前的校验
  const beforeImageUpload = (file: File) => {
    const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJPGorPNG) {
      ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
    }
    if (!isLt2M) {
      ElMessage.error('上传图片大小不能超过 2MB!');
    }
    return isJPGorPNG && isLt2M;
  };
  
  // 提交表单
  const submitForm = () => {
    productForm.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          // 提交商品数据到后端接口
          const response = await axios.post('/api/products', product.value);
          const productId = response.data.data.id; // 获取新创建商品的ID
                console.log('新创建商品的ID:', response);
                
          // 如果商品分类是表情包，提交表情包列表
          if (product.value.categoryId === 2 && emojiList.value.length > 0) {
            // 设置表情包的 productId 并提交表情包列表
            const emojiData = emojiList.value.map(emoji => ({
              ...emoji,
              productId
            }));
            console.log('表情包数据:', emojiData);
            
            await axios.post('/api/emojis/create/list', emojiData);
          }
  
          ElMessage.success('商品创建成功');
          router.push('/product_list_show');
        } catch (error) {
          ElMessage.error('商品创建失败');
          console.error(error);
        }
      } else {
        ElMessage.error('请填写所有必填项');
      }
    });
  };

  // 引用表单
  const productForm = ref();
  
  // 重置表单
  const resetForm = () => {
    productForm.value.resetFields();
    emojiList.value = []; // 重置表情包列表
  };
  </script>
  
  <style scoped>
  .compact-form {
    padding: 20px;
  }
  
  .el-form-item {
    margin-bottom: 10px;
  }
  </style>
  